package com.geek.water.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geek.water.entity.UserRole;
import com.geek.water.mapper.UserRoleMapper;
import com.geek.water.service.UserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenmin
 * @desc 用户角色关联服务实现类
 * @date 2025/8/5
 */
@Service
@Slf4j
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Override
    public List<Long> getRoleIdsByUserId(Long userId) {
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, userId);
        List<UserRole> userRoles = baseMapper.selectList(queryWrapper);
        return userRoles.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public boolean assignRolesToUser(Long userId, List<Long> roleIds) {
        try {
            // 先删除用户的所有角色
            deleteRolesByUserId(userId);

            // 如果没有角色ID，直接返回成功
            if (roleIds == null || roleIds.isEmpty()) {
                return true;
            }

            // 批量插入新的角色关联
            List<UserRole> userRoles = roleIds.stream()
                    .map(roleId -> {
                        UserRole userRole = new UserRole();
                        userRole.setUserId(userId);
                        userRole.setRoleId(roleId);
                        return userRole;
                    })
                    .collect(Collectors.toList());

            return saveBatch(userRoles);
        } catch (Exception e) {
            log.error("为用户分配角色失败，用户ID: {}, 角色IDs: {}", userId, roleIds, e);
            return false;
        }
    }

    @Override
    public boolean deleteRolesByUserId(Long userId) {
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, userId);
        return baseMapper.delete(queryWrapper) >= 0;
    }
}
